var selectedTimeSpan = getCookie("_span");
if (selectedTimeSpan==null || selectedTimeSpan == "")selectedTimeSpan = 3;
var selectedDate = new Date();
var hotelId = -1;
var ShortDay = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var ShortMonth = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var currencyDecimalPlaces = 0;
var dateFormatString = 'd M yy';
var optionString = '<option value="{0}">{1}</option>';
var optionStringWithAttr = '<option value="{0}" attr="{2}">{1}</option>';
var dynamicScript={};

Date.prototype.getFormatedString=function(){return $.datepicker.formatDate(dateFormatString,this,{monthNamesShort:ShortMonth,monthNames:ShortMonth,dayNamesShort:ShortDay,dayNames:ShortDay})}
Date.prototype.getFormatedDateTime=function(){return this.getFormatedString() + " " + this.getHours() + ":" + this.getMinutes()}
Date.prototype.getFormatedDateAndMonthString=function(){dateFormatString_=dateFormatString.replace(/y/g,"");dateFormatString_=$.trim(dateFormatString_.replace("  "," "));return $.datepicker.formatDate(dateFormatString_,this,{monthNamesShort:ShortMonth,monthNames:ShortMonth,dayNamesShort:ShortDay,dayNames:ShortDay})}
String.prototype.getDate=function(){return $.datepicker.parseDate(dateFormatString,this,{monthNamesShort:ShortMonth,monthNames:ShortMonth,dayNamesShort:ShortDay,dayNames:ShortDay})}

Date.prototype.toFormatString = function(stringFormat) {
	var result = stringFormat;
	result = result.replace("ddd",ShortDay[this.getDay()]);
	result = result.replace("dd",this.getDate());
	result = result.replace("MMM",ShortMonth[this.getMonth()]);
	result = result.replace("MM",this.getMonth() + 1);
	result = result.replace("yyyy",this.getFullYear());
	result = result.replace("hh",this.getHours());
	result = result.replace("mm",this.getMinutes());
	return result;
};
Date.prototype.toSystemFormat = function(){return this.toFormatString("yyyy-MM-dd")}
Date.prototype.addDate=function(e){var t=new Date(this);t.setDate(t.getDate()+e);return t}
Date.prototype.addMin=function(e){return new Date(this.getTime()+e*6e4)}
String.prototype.format=function(){var e=this;for(var t=0;t<arguments.length;t++){var n="{"+t+"}";e=e.replace(n,arguments[t])}return e}

$.fn.equals=function(e){if(!e||this.length!=e.length){return false}for(var t=0;t<this.length;++t)if(this[t]!==e[t])return false;return true}

var daysBetween=function(e,t){return(t-e)/864e5}

function getCookie(c_name){var i,x,y,ARRcookies=document.cookie.split(";");for(i=0;i<ARRcookies.length;i++){x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);x=x.replace(/^\s+|\s+$/g,"");if(x==c_name)return unescape(y)}}
function setCookie(c_name,value,exdays){var exdate=new Date();exdate.setDate(exdate.getDate()+exdays);var c_value=escape(value)+((exdays==null)?"":"; expires="+exdate.toUTCString());document.cookie=c_name+"="+c_value}
function setCookieMins(e,t,n){var r=new Date((new Date).getTime()+n*6e4);var i=escape(t)+(n==null?"":"; expires="+r.toUTCString());document.cookie=e+"="+i}

function componentLoading(e){if(e.attr("loading_id")!=null)return;var t=Math.random().toString(16).slice(2,10)+Math.random().toString(16).slice(2,10)+"_loading";e.attr("loading_id",t);if(e.children(0).size()==0)e.append('<div id="'+t+'" class="component_loading"><img src="/images/loading.gif"></div>');else e.children(0).first().before('<div id="'+t+'" class="component_loading"><img src="/images/loading.gif"></div>');$("#"+t).width(e.width());$("#"+t).height(e.height());$("#"+t+" img").css("margin-top",(e.height()-32)/2)}
function closeComponentLoading(e){var t=e.attr("loading_id");e.removeAttr("loading_id");$("#"+t).remove()}

function dynamicLoadingCustomDialog(dynamicDom,title,file,buttons,loadFilefinish,args){
	var dialog = null;
	var obj = {
		title:title,dialog:dialog,buttons:buttons,
		args:args,loadFilefinish:loadFilefinish	
	};
	loadDynamicJSP(dynamicDom,file,function(obj){
		obj.dialog = customDialog(obj.title,"<div id='loadingScreen'></div>",null,null,obj.args);
	},function(resp,obj){
		if(obj.dialog!=null){
			obj.dialog.find(".ui-newdialog-content").html(resp);
			bindButtonDialog(obj.dialog,obj.buttons,obj.args);
		}
		else{
			obj.dialog = customDialog(obj.title,resp,null,obj.buttons,obj.args);
		}
		if(obj.loadFilefinish!=null) obj.loadFilefinish(obj.dialog,obj.args);
	},obj);
}
function simpleDialog(message,delay,callback){
	var buttons = [
		{ title:"OK", attr: " from='simpledialog'" , callback: function(thisdialog,args){
			thisdialog.dialog("close");
			if((delay == null || delay == 0) && callback != null) callback();
		}}
	];
	if(delay!= null && delay != 0)
		setTimeout(function(){
			var dialog = customDialog(simpleLabel_Message,message,null,buttons,null);
			dialog.css("overflow","hidden");
			dialog.find(".colse_icon").attr("from",'simpledialog');
			callback();
		},delay);
	else{
		var dialog = customDialog(simpleLabel_Message,message,null,buttons,null);
		dialog.css("overflow","hidden");
		dialog.find(".colse_icon").attr("from",'simpledialog');
	}
}
function confirmDialog(message,callback,args)
{
	var content = message;
	var buttons = [
		{ title:"OK", callback: function(thisdialog,args){
			thisdialog.dialog("close");
			callback(args);
		}},
		{ title:"Cancel", callback: function(thisdialog,args){
			thisdialog.dialog("close");
		}}
	];
	//var size = { width: 700, height: 200};
	return customDialog(simpleLabel_Message,content,null,buttons,args);
}
function customDialog(title,content,size,arrayButton,args){
	if(title == null) title = simpleLabel_Message;
	if($("#loadingScreen").is(":visible")) closeWaitingDialog();
	var msgDialog = $("#BlankDialog").clone();
	msgDialog.dialog({
		resizable : false,
		title: title,
		modal: true,
		close: function() { msgDialog.dialog('destroy').remove(); },
		open: function() {
			if(size != null && size.width != null){
				msgDialog.parent().css("width",size.width);
				msgDialog.parent().css("left",'50%');
				msgDialog.parent().css("margin-left",-(size.width/2));
			}
			if(size != null && size.height != null){
				msgDialog.parent().css("to",'50%');
				msgDialog.parent().css("margin-top",-(size.height/2));
			}
		}
	});
	var maxZ = MaxDivZIndex();
	msgDialog.parent().find('.ui-dialog-titlebar').css("display","none");
	msgDialog.parent().css("z-index",maxZ+2);
	msgDialog.parent().next().css("z-index",maxZ+1);
	//msgDialog.parent().find('')
	msgDialog.css("padding",0);
	msgDialog.css("margin",0);
	var classHeight = (size != null && size.height != null)? ' style="height:'+size.height+'px !important;"' : "";
	msgDialog.html('<div class="ui-newdialog-titlebar"><div>'+title+'<span class="colse_icon " style="float:right"></span></div></div>' +
		'<div class="ui-newdialog-content"'+classHeight+'>'+content+'</div>' +
		'<div class="ui-newdialog-button"><div style="text-align:center;"></div></div>');
	msgDialog.find(".colse_icon").click(function() {msgDialog.dialog("close");});

	var tmpP = msgDialog.parents(".ui-dialog:first");
	tmpP.parent().find("ui-widget-overlay").css("z-index",tmpP.css("z-index")-1);
	if(arrayButton != null)
	for(var i=arrayButton.length-1;i>=0;i--)
	{
		var style = (arrayButton[i].style != null)? arrayButton[i].style : "float:right";
		var attr = (arrayButton[i].attr != null)? arrayButton[i].attr : "";
		var btn = $('<button style="'+style+'" class="btn" '+attr+'>' + arrayButton[i].title + '</button>');
		btn.bind('click', arrayButton[i], function(event) {
			event.data.callback(msgDialog,args);
		});
		msgDialog.find(".ui-newdialog-button div").append(btn);
	}
	msgDialog.dialog({draggable: false}).parent().draggable({handle:'.ui-newdialog-titlebar'});

	return msgDialog;
}
function bindButtonDialog(msgDialog,arrayButton,args){if(arrayButton!=null)for(var i=arrayButton.length-1;i>=0;i--){var style="float:right";if(arrayButton[i].style!=null)style=arrayButton[i].style;var btn=$('<button style="'+style+'" class="btn">'+arrayButton[i].title+'</button>');btn.bind('click',arrayButton[i],function(event){event.data.callback(msgDialog,args)});msgDialog.find(".ui-newdialog-button div").append(btn)}}
function MaxDivZIndex(){var maxZ = 100000;$('div').each(function () { var z = parseInt($(this).css('z-index')); if (z > maxZ && z < 1000000) maxZ = z; });return maxZ;}

var SharedData = {};
var sequenceOnload = [];
function loadSharedData(callback)
{
	//moved: Salutation,Package,RoomTax,PayModeAndPayType,SourcesBusiness,loadAllModeArrival
	//moved delay load: CancelReason
	var services = [];
	services.push(["/popupService",{doClass : "loadGeneral"},function(data,args) { SharedData.General = JSON.parse(data);},null]);
	services.push(["/roomtypeService",{func : "getAllRoomtype"},function(data,args) { SharedData.RoomType = JSON.parse(data);},null]);
	services.push(["/roomService",{ func: "getShowRooms"},function(data,args) { SharedData.Room = JSON.parse(data);},null]);
	services.push(["/popupService",{ doClass : "loadResvStatus" },function(data,args) { SharedData.ResvStatus = JSON.parse(data);},null]);
	services.push(["/popupService",{ doClass : "loadCleaningStatus" },function(data,args) { SharedData.CleaningStatus = JSON.parse(data);},null]);
	services.push(["/cancellationpolicyService",{func:"getCancellationPolicy"},function(data,args) { SharedData.CancellationPolicy = JSON.parse(data); },null]);
	arrayservice(services,LoadSharedServiceSuccess,callback);
}
function loadSharedDataIfNotExist(e,t,n){var r=[];for(var i=0;i<e.length;i++)if(SharedData[e[i][2]]==null){var s=e[i][2];e[i][2]=function(e,t){SharedData[t]=JSON.parse(e)};e[i][3]=s;r.push(e[i])}if(r.length!=0)arrayservice(r,t,n);else if(t!=null)t(n)}
//*** filter SharedData ***//
function LoadSharedServiceSuccess(callback)
{
	currencyDecimalPlaces = SharedData.General.currencyDecimalPlaces;
	dateFormatString = SharedData.General.dateFormat.dateTimeFormat;

	for(var i=0;i<sequenceOnload.length;i++)
		sequenceOnload[i]();
	closeComponentLoading($(".setright table"));
	callback();
}
function getRoomTypeId(id){return getObjectFromSharedData(SharedData.RoomType,id);}
function getObjectFromSharedData(e,t){if(e==null)return null;for(var n=0;n<e.length;n++)if(e[n].id==t)return e[n];return null}
function getObjectFromDataIndex(e,t,n){if(e==null)return null;for(var r=0;r<e.length;r++)if(e[r][t]==n)return e[r];return null}
function getObjectFromDataIndexArray(e,t,n){var r=null;for(var i=0;i<e.length;i++){var s=e[i];for(var o=0;o<t.length;o++)s=s[t[o]];if(s==n){r=e[i]}}return r}
function getListFromDataIndex(obj,field,id)
{
	var rs = [];
	for(var i=0;i<obj.length;i++)
		if(obj[i][field] == id) rs.push(obj[i]);
	return rs;
}
function getListOfFieldId(obj,field)
{
	var all = [];
	var rs = [];
	for(var i=0;i<obj.length;i++)
		all.push(obj[i][field]);
	$.each(all, function(i, el){
		if($.inArray(el, rs) === -1) rs.push(el);
	});
	return rs;
}
function filedStringOfList(obj,fields){
	var rs="";
	$.each(obj,function(k,v){
		w=v;
		for(i=0;i<fields.length;i++) w=w[fields[i]];
		rs+=w+","
	});
	return rs.substring(0, rs.length-1);
}
function filedListOfList(obj,fields){
	var rs=[];
	$.each(obj,function(k,v){
		w=v;
		for(i=0;i<fields.length;i++) w=w[fields[i]];
		rs.push(w);
	});
	return rs;
}

function getServerDateTime()
{
	var dateNow = new Date();
	var serCompareTime = getCookie("CompareTime");
	var servaerDate =dateNow.getTime()+parseInt(serCompareTime);
	return new Date (servaerDate);
}

// return only Date;
function getDate()
{
	var naTime = new Date(SharedData.General.nightAuditTime);
	naTime.getHours();
	naTime.getMinutes();
	naTime.getSeconds();
	var time = naTime.getHours()+":"+naTime.getMinutes()+":"+naTime.getSeconds();
	if(parseDateTime(getServerDateTime().toSystemFormat() +" "+time).getTime() < getServerDateTime().getTime())
		return $.datepicker.parseDate("yy-mm-dd",getServerDateTime().toSystemFormat());
	else
		return $.datepicker.parseDate("yy-mm-dd",getServerDateTime().addDate(-1).toSystemFormat());
}
//for currency
function toCurrencyString(e,t){var n=e.toFixed(SharedData.General.currencyDecimalPlaces).replace(/(\d)(?=(\d{3})+\.)/g,"$1,");if(!t)n=SharedData.General.defaultCurrency.symbol+" "+n;return n}
function currencyStringToNumber(e){return Number(e.replace(/[^0-9\.]+/g,""))}

// sort object
function sortIdPrint(objArray){
	objArray.sort(function (a,b){ return b.displayId - a.displayId; });
	return objArray;
}
function sortIdRoommanagement(objArray){
	objArray.sort(function (a,b){ return a.displayId - b.displayId; });
	return objArray;
}
function sortDateRoommanagement(objArray){
	objArray.sort(function (a,b){ return parseInt(new Date(a.date).getTime()) - parseInt(new Date(b.date).getTime()); });
	return objArray;
}

$.getScriptIfNotExist=function(e,t){if(dynamicScript[e]!=null)return $.get();dynamicScript[e]=true;return $.getScript(e,t)}
function parseDateTime(e){var t=e.split(" ")[1].split(":");var n=$.datepicker.parseDate("yy-mm-dd",e.split(" ")[0]);n.setHours(t[0]);n.setMinutes(t[1]);n.setSeconds(t[2]);return n}

function CheckAllScript(AryScriptName,callBack,Args)
{ 
	var t=0;
	for(var n=0;n<AryScriptName.length;n++)
	{
		$.getScriptIfNotExist(AryScriptName[n]).done(function(script,textStatus)
		{ 
			t++;
			if(t== AryScriptName.length)
				callBack(Args);
		});
	}
}

function toHexColor(e){if(e.search("rgb")==-1)return e;else{e=e.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);function t(e){return("0"+parseInt(e).toString(16)).slice(-2)}return"#"+t(e[1])+t(e[2])+t(e[3])}}
function LightenDarkenColor(e,t){var n=false;if(e[0]=="#"){e=e.slice(1);n=true}var r=parseInt(e,16);var i=(r>>16)+t;if(i>255)i=255;else if(i<0)i=0;var s=(r>>8&255)+t;if(s>255)s=255;else if(s<0)s=0;var o=(r&255)+t;if(o>255)o=255;else if(o<0)o=0;return(n?"#":"")+(o|s<<8|i<<16).toString(16)}

function loadDynamicJSP(dom,file,callbackBeforeLoad,callbackAfterLoad,args){
	file_ = file.substr(0,file.lastIndexOf("."));
	if(dom.find("div[file='"+file_+"']").size()==0){
		if(callbackBeforeLoad!=null) callbackBeforeLoad(args);
		var div = $("<div file='"+file_+"'>").load(file,function(responseText, textStatus, XMLHttpRequest) {
			var args = document.TmpDynamicLoadJSP;
			var callbackAfterLoad = document.TmpDynamicLoadCallbackJSP;
			delete document.TmpDynamicLoadJSP;
			delete document.TmpDynamicLoadCallbackJSP;
			if(callbackAfterLoad!=null) callbackAfterLoad(responseText,args);
		});
		dom.append(div);
		document.TmpDynamicLoadJSP = args;
		document.TmpDynamicLoadCallbackJSP = callbackAfterLoad;
	}else{
		var content = dom.find("div[file='"+file_+"']").html()
		callbackAfterLoad(content,args);
	}
}

function CheckSession(objArray){
	if(objArray.result==false){
		var buttons = [{ title:"OK" , callback: function(thisdialog,args){window.location.assign("logout.jsp");}}];
   		customDialog(Warning,ForceLogout,null,buttons,null);
   		return true;
	}
}

function isCurrency()/*onkeypress='return isCurrency()'*/{if(isNumberKey(event))return true;if(event.keyCode==46&&$(event.target).val().indexOf(".")<0)return true;return false}
function alertMessage(e,t,n)/*text,time,top*/{if(t==null)t=5e3;if($("#alertmessage").size()==0){var r=$('<div id="alertmessage">'+e+"</div>");$("body").append(r);r.css("margin-left",r.width()*-.5);if(n==null&&$(document).scrollTop()<26)r.css("top","50px");if(n!=null)r.css("top",n+"px");document.windowsetTimeout=window.setTimeout(function(){$("#alertmessage").fadeOut(300,function(){$("#alertmessage").remove()})},t)}else{clearTimeout(document.windowsetTimeout);$("#alertmessage").html(e);document.windowsetTimeout=window.setTimeout(function(){$("#alertmessage").fadeOut(300,function(){$("#alertmessage").remove()})},t)}}
function guid(){var e=(new Date).getTime();var t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var n=(e+Math.random()*16)%16|0;e=Math.floor(e/16);return(t=="x"?n:n&7|8).toString(16)});return t}
function ForceNumericOnly(el){return el.each(function(){$(this).keydown(function(e){var t=e.charCode||e.keyCode||0;return t==8||t==9||t==46||t==110||t==190||t>=35&&t<=40||t>=48&&t<=57||t>=96&&t<=105})})}
function calPriceWithoutTax(displayPrice,perc,fix,_incTax){if(_incTax==null||_incTax=="")_incTax=SharedData.General.incloudetax;if(!_incTax)return displayPrice;else return(displayPrice-fix)/((perc/100)+1)}
function customCalTax(priceWithoutTax,perc,fix,_discount,_amount,_incTax){if(_discount==null||_discount=="")_discount=0;if(_amount==null||_amount=="")_amount=1;if(_incTax==null||_incTax=="")_incTax=SharedData.General.incloudetax;var rs={};if(!_incTax){var priceBeforeTax=(priceWithoutTax*_amount)-_discount;var tax=((priceBeforeTax*perc)/100)+(fix*_amount);rs.totalPrice=priceBeforeTax+tax;rs.totalPriceBeforeTax=priceBeforeTax;rs.totalTax=tax;rs.displayPricePerUnitBeforeDiscount=priceWithoutTax}else{var taxPerUnit=((priceWithoutTax*perc)/100)+fix;var priceIncTax=priceWithoutTax+taxPerUnit;var priceAfterDiscount=(priceIncTax*_amount)-_discount;var priceBeforeTax=(priceAfterDiscount-(fix*_amount))/(1+(perc/100));var tax=((priceBeforeTax*perc)/100)+(fix*_amount);rs.totalPrice=priceAfterDiscount;rs.totalPriceBeforeTax=priceBeforeTax;rs.totalTax=tax;rs.displayPricePerUnitBeforeDiscount=priceIncTax}return rs}